package masking.wechat.sdk.h5;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import masking.wechat.sdk.MPAccount;
import masking.wechat.sdk.SimpleCache;
import masking.wechat.sdk.mp.MpAccessTokenUtil;
import masking.wechat.sdk.util.HttpUtils;

public class MpJsapiTicket {

	private static final String MP_JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=";
	
	private static final Map<String, SimpleCache<String>> TICKET_MAP = new ConcurrentHashMap<>();

	public static String get(MPAccount mp) throws IOException {
		SimpleCache<String> ticket =TICKET_MAP.get(mp.getAppId());
		if (ticket != null) {
			Date now = new Date();
			if (now.before(ticket.expireTime)) {
				return ticket.data;
			}
		}
		return refresh(mp);
	}

	private synchronized static String refresh(MPAccount mp) throws IOException {
		SimpleCache<String> ticket =TICKET_MAP.get(mp.getAppId());
		if (ticket != null) {
			Date now = new Date();
			if (now.before(ticket.expireTime)) {
				return ticket.data;
			}
		}

		String response = HttpUtils.get(MP_JSAPI_TICKET_URL + MpAccessTokenUtil.get(mp));
		JSONObject json = new JSONObject(response);
		String newTicket = json.getString("ticket");
		if (StringUtils.isNotBlank(newTicket)) {
			Calendar c = Calendar.getInstance();
			c.add(Calendar.HOUR, 1);
			ticket = new SimpleCache<String>(newTicket, c.getTime());
			TICKET_MAP.put(mp.getAppId(), ticket);
			return ticket.data;
		} else {
			return null;
		}

	}
}
